package com.sk.sourcecircle.activity.mine.act;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.kyleduo.switchbutton.SwitchButton;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.common.Constants;
import com.sk.sourcecircle.dialog.CustomPhoneDialogFragment;
import com.sk.sourcecircle.dialog.ShareDialogFragment;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.HomePageInfo;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.DataCleanManager;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SPUtils;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/11/23.
 */

@RuntimePermissions
public class SystemSettingsActivity extends BaseActivity implements HandleDataCallBack, IUiListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.add_friend)
    SwitchButton addFriend;
    @BindView(R.id.allow_look)
    SwitchButton allowLook;
    @BindView(R.id.message)
    RelativeLayout message;
    @BindView(R.id.share)
    RelativeLayout share;
    @BindView(R.id.cache_num)
    TextView cacheNum;
    @BindView(R.id.clear)
    RelativeLayout clear;
    @BindView(R.id.statement)
    RelativeLayout statement;
    @BindView(R.id.contact_us)
    RelativeLayout contactUs;
    @BindView(R.id.version)
    RelativeLayout version;

    private HomePageInfo.DataBean.UserInfoBean myInfo;
    private LoadingDialog loadingDialog;
    private String phone = "18970056828";

    @Override
    protected int getContentView() {
        return R.layout.activity_system_settings;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myInfo = getIntent().getParcelableExtra("data");

        if (myInfo.getAdd_auth() == 0) {
            addFriend.setChecked(true);
        } else {
            addFriend.setChecked(false);
        }

        if (myInfo.getShow_auth() == 0) {
            allowLook.setChecked(false);
        } else {
            allowLook.setChecked(true);
        }

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        try {
            cacheNum.setText(DataCleanManager.getTotalCacheSize(mContext));
        } catch (Exception e) {
            e.printStackTrace();
        }

        addFriend.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    loadingDialog.show();
                    AppApi.settingAddFriend(MyUtils.getCode(mContext), 0, SystemSettingsActivity.this, 2, SystemSettingsActivity.this);
                } else {
                    loadingDialog.show();
                    AppApi.settingAddFriend(MyUtils.getCode(mContext), 1, SystemSettingsActivity.this, 2, SystemSettingsActivity.this);
                }
            }
        });

        allowLook.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    loadingDialog.show();
                    AppApi.setStrangerIsLook(MyUtils.getCode(mContext), 1, SystemSettingsActivity.this, 2, SystemSettingsActivity.this);

                } else {
                    loadingDialog.show();
                    AppApi.setStrangerIsLook(MyUtils.getCode(mContext), 0, SystemSettingsActivity.this, 2, SystemSettingsActivity.this);

                }
            }
        });
    }

    @OnClick({R.id.back, R.id.share, R.id.clear, R.id.statement, R.id.contact_us, R.id.version, R.id.login_out})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.share:
                ShareDialogFragment shareDialogFragment = new ShareDialogFragment();
                shareDialogFragment.setTargetUrl(Constants.App_url);
                shareDialogFragment.setImageUrl("");
                shareDialogFragment.setQqListener(this);
                shareDialogFragment.setTitle("源圈");
                shareDialogFragment.setSummary("源圈社区”是北京源圈传媒科技有限公司自主开发运营的一款APP应用，是消费升级领域首家本地化精准数据匹配平台。以本地化社群APP为载体，用户运营为中心，串连社区、中小微企业、校园三大场景，运用“去中心化”的平台方式，让各实体社群实现精准用户运营、精准需求匹配、精准营销推广。立志成为一个让人人都能实现价值的平台、一个基于实体场景的精准大数据平台。");
                shareDialogFragment.show(getFragmentManager(), "share");
                break;
            case R.id.clear:
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setMyCallBack(SystemSettingsActivity.this);
                tipDialogFragment.setContent("确认清除缓存？");
                tipDialogFragment.show(getSupportFragmentManager(), "clear");
                break;
            case R.id.statement:
                Intent intent = new Intent(mContext,AgreementActivity.class);
                startActivity(intent);
                break;
            case R.id.contact_us:
                SystemSettingsActivityPermissionsDispatcher.startCallWithPermissionCheck(SystemSettingsActivity.this);
                break;
            case R.id.version:
                Intent aboutIntent = new Intent(mContext,AboutActivity.class);
                startActivity(aboutIntent);
                break;
            case R.id.login_out:
                TipDialogFragment tipDialogFragment1 = new TipDialogFragment();
                tipDialogFragment1.setMyCallBack(new MyCallBack() {
                    @Override
                    public void releaseAlbum() {

                    }

                    @Override
                    public void joinGroup() {

                    }

                    @Override
                    public void takePhoto() {

                    }

                    @Override
                    public void choosePhoto() {

                    }

                    @Override
                    public void sure() {
                        EMClient.getInstance().logout(true, new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                SPUtils.clear(mContext);
                                setResult(RESULT_OK);
                                finish();
                            }

                            @Override
                            public void onError(int code, String error) {

                            }

                            @Override
                            public void onProgress(int progress, String status) {

                            }
                        });
                    }

                    @Override
                    public void cancelOder(String string) {

                    }

                    @Override
                    public void chooseGroup(String id) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void sendText(String comment) {

                    }
                });
                tipDialogFragment1.setContent("确认退出登录？");
                tipDialogFragment1.show(getSupportFragmentManager(), "clear");
                break;
        }
    }

    @Override
    public void sure() {
        super.sure();
        DataCleanManager.clearAllCache(mContext);
        cacheNum.setText("0MB");
        Toast.makeText(mContext, "缓存清除成功！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        Toast.makeText(mContext, "设置成功!", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {

    }

    @Override
    public void onCancel() {

    }


    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void startCall() {
        CustomPhoneDialogFragment customPhoneDialogFragment = new CustomPhoneDialogFragment();
        customPhoneDialogFragment.setContent("189-7005-6828");
        customPhoneDialogFragment.setMyCallBack(new MyCallBack() {
            @Override
            public void releaseAlbum() {

            }

            @Override
            public void joinGroup() {

            }

            @Override
            public void takePhoto() {

            }

            @Override
            public void choosePhoto() {

            }

            @Override
            public void sure() {
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + phone);
                intent.setData(data);
                startActivity(intent);
            }

            @Override
            public void cancelOder(String string) {

            }

            @Override
            public void chooseGroup(String id) {

            }

            @Override
            public void cancel() {

            }

            @Override
            public void sendText(String comment) {

            }
        });
        customPhoneDialogFragment.show(getSupportFragmentManager(), "phone");
    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showRationaleForPhone(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的电话！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showDeniedForPhone() {
        Toast.makeText(mContext, "拒绝", Toast.LENGTH_SHORT).show();
    }


    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showNeverAskForPhone() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止电话权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SystemSettingsActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


}
